#! /usr/bin/env python

# Client and server for udp (datagram) echo.
#
# Usage: udpecho -s [port]            (to start a server)
# or:    udpecho -c host [port] <file (client)

import sys

from socket import *
from Point import *
from Robot import *
from environment import *


MODULE = 'MyTeam'
ECHO_PORT = 5151
BUFSIZE = 1024

strategyModule = __import__(MODULE, "","",['strategy'])

def main():
    if len(sys.argv) < 2:
        usage()
    if sys.argv[1] == '-s':
        server()
    else:
        usage()

def usage():
    sys.stdout = sys.stderr
    print 'Usage: proxy -s [port]            (server)'
    sys.exit(2)

def server():
    if len(sys.argv) > 2:
        port = eval(sys.argv[2])
    else:
        port = ECHO_PORT
    s = socket(AF_INET, SOCK_DGRAM)
    s.bind(('', port))
    print 'udp echo server ready'
    strategy = strategyModule.strategy
    while 1:
        data, addr = s.recvfrom(BUFSIZE)
        env = parseEntry(data)
        strategy(env)
        response = env.toSend()
        s.sendto(response, addr)       

def parseEntry(str):
    #here we parse the comming data
    data = str.split(":")
    envList = data[1:3]
    currentBallList = []
    currentBallList.append(float(data[3]))
    currentBallList.append(float(data[4]))
    lastBallList = data[5:7]
    envList.append(Point(currentBallList))
    envList.append(Point(lastBallList))
    
    myBots = data[7:7+(5*3)]
    myBotList = []
    
    n = 0
    for i in range(5):
        myBotList.append(MyRobot(myBots[n:n+3]))
        n = n + 3
        
    envList.append(myBotList)
        
    opponentBots = data[7+(5*3):]
    opponentBotList = []
    
    n = 0
    for i in range(5):
        opponentBotList.append(Robot(opponentBots[n:n+3]))
        n = n + 3
        
    envList.append(opponentBotList)
    env = Environment(envList)
    return env

def test():
    str = '2:0:0:49.988789:41.487717:0.000000:0.000000:90.469604:42.129551:-90.107857:82.099602:22.957527:-179.828293:81.295959:60.434010:179.862137:61.852398:23.127762:-179.669891:61.439579:60.399273:179.953033:10.662151:42.245323:89.828812:19.922005:60.403706:0.294860:19.736788:23.047390:-0.344825:39.455231:60.333862:0.343221:39.886448:23.083376:-0.306789'
    env = parseEntry(str)
    print env
    st = env.toSend()
    print st
    print "end"
    
if __name__ == "__main__":
    main()
    #test()
    